package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login")
    public ResponseBodyMessage<Boolean> userLogin(@RequestBody User user, HttpServletRequest request) {
        User truUser = userService.selectByUserName(user.getUsername());
        if (truUser == null) {
            System.out.println("登录失败!");
            return new ResponseBodyMessage<>(-1, "用户名密码错误!", false);
        } else {
            boolean flg = bCryptPasswordEncoder.matches(user.getPassword(), truUser.getPassword());
            if (!flg) {
                return new ResponseBodyMessage<>(-1, "用户名密码错误!", false);
            }
            System.out.println("登录成功!");
            HttpSession session = request.getSession(true);
            System.out.println(session);
            session.setAttribute("user", truUser);
            return new ResponseBodyMessage<>(1, "登录成功!", true);
        }
    }


    @RequestMapping("/register")
    public ResponseBodyMessage<User> register(@RequestBody User user) {
        if(user.getUsername() == null || "".equals(user.getUsername().trim())
                || user.getPassword() == null || "".equals(user.getPassword().trim())){
            return new ResponseBodyMessage<>(-1,"输入内容为空!",null);
        }
        User truUser = userService.selectByUserName(user.getUsername());
        if (truUser != null) {
            return new ResponseBodyMessage<>(-1,"当前用户名已经存在!",null);
        } else{
            String password = bCryptPasswordEncoder.encode(user.getPassword());
            user.setPassword(password);

            userService.addUser(user);
            return new ResponseBodyMessage<>(1,"注册成功!",user);
        }
    }

    @RequestMapping("/logout")
    public void userLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession(false);
        // 拦截器的拦截, 所以不可能出现session为空的情况
        session.removeAttribute("user");
        response.sendRedirect("login.html");
    }

}
